package com.ddh.codeduck.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ddhcodeduck.common.utils.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


// 2. 配置自动填充处理器（需实现 MetaObjectHandler）
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间、创建者
        this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createdBy", String.class, getCurrentUserId());
        String tableName = metaObject.getOriginalObject().getClass().getSimpleName();
        if ("CodeDuckQuestion".equals(tableName)) {
            // 只针对题目表设置status默认值
            this.strictInsertFill(metaObject, "status", String.class, "PENDING");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间、更新者
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updatedBy", String.class, getCurrentUserId());
    }

    private String getCurrentUserId() {
        // 从上下文获取当前用户ID
        return UserContextHolder.getUserId();
    }
}
